﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMenuBar>
#include <QMenu>
#include <QTextEdit>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建文本输出区域
    auto *output = new QTextEdit(this);
    output->setReadOnly(true);
    setCentralWidget(output);

    // 加载插件
    PluginManager::instance().loadPlugins(qApp->applicationDirPath() + "/plugins");

    // 创建菜单
    QMenu *pluginMenu = menuBar()->addMenu(tr("Plugins"));
    const auto &plugins = PluginManager::instance().plugins();

    for (IAlgorithmPlugin *plugin : plugins) {
        QAction *action = new QAction(plugin->name(), this);
        pluginMenu->addAction(action);
        pluginActions[action] = plugin;
        connect(action, &QAction::triggered, this, &MainWindow::onPluginTriggered);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onPluginTriggered()
{
    QAction *action = qobject_cast<QAction *>(sender());
    if (!action || !pluginActions.contains(action))
        return;

    IAlgorithmPlugin *plugin = pluginActions[action];

    // 创建输入数据
    const int size = 10;
    double* in = new double[size];
    for(int i=0;i<size;i++)
    {
        in[i] = i*10;
    }

    std::unique_ptr<AlgorithmConfigBase> conf = std::make_unique<AlgorithmConfigFoo>();
    // 算法配置
    plugin->config(conf);

    // 算法分析接口
    auto basePtr = plugin->analyze(in, size);
    auto foo = dynamic_cast<AlgorithmResultFoo*>(basePtr.get());
    // 打印分析结果
    QStringList strList;
    for (QVariant val : foo->vec) {
        strList << val.toString();
    }
    QString vecStr = strList.join(", ");  // "1.1, 2.2, 3.3"

    QTextEdit *output = qobject_cast<QTextEdit *>(centralWidget());
    if (output) {
        output->append(vecStr);
    }
}
